<template>
    <div class="show_code_block">
        <div class="bar">
            <span class="showLang">{{language}}</span>
            <p class="copy">
                <i class="el-icon-copy-document"></i>
                <el-button type="text" @click="copyCode">复制</el-button>
            </p>
        </div>
        <pre v-if="formattedCode"><code ref="codeBlock" v-html="formattedCode"></code></pre>
    </div>
</template>

<script>
  import hljs from 'highlight.js';
  import 'highlight.js/styles/default.css';
  export default {
    props: {
      code: {
        type: String,
        required: true
      },
      language: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        formattedCode: ''
      };
    },
    mounted() {
      this.formatCode();
    },
    methods: {
      copyCode() {
        try{
          navigator.clipboard.writeText(this.code);
          this.$message.success('复制成功');
        }catch(e){
          console.log(e)
        }
      },
      formatCode() {
        const lines = this.code.split('\n');
        this.formattedCode = lines.map((line, index) => {
          return `<span>${index + 1}</span> ${line}`;
        }).join('\n');
        this.$nextTick(() => {
          if (this.$refs.codeBlock) {
            hljs.highlightBlock(this.$refs.codeBlock);
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
    .show_code_block{
        position: relative; background-color: #F3F3F3;padding: 34px 0 10px;
        .bar{
            display: none;position:absolute; top:10px; right: 10px; left: 10px;
            .copy{position:absolute; cursor: pointer; right: 0; display: inline-block; max-width: 60px; margin: 0; top:0;}
            .el-button{padding-top: 2px; }
            .showLang{position:absolute;left: 0; color: #245bdb;}
        }
        &:hover {
          .bar{display: block;}
        }
        pre {
            position: relative; margin: 0;
        }
        pre code {
            display: block; /* 使code标签成为块级元素 */
            white-space: pre-wrap; /* 保持空白符和换行 */
            font-size: 16px;
        }

    }
</style>

<style lang="scss">
    .show_code_block{
        .hljs-symbol{
            display: inline-block;
            width: 24px; /* Adjust the width as needed */
            text-align: right;
            margin-right:20px; /* Adjust the margin as needed */
            color: #888; /* Adjust the line number color as needed */
        }
        pre code.hljs{padding-top: 0}
    }
</style>






